<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>批量导入</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../css/oksub.css">
    <script src="../../lib/layui/layui.js"></script>
    <script type="text/javascript">
        // 获取contentText
        const ctx = function () {
            let pathName = document.location.pathname;
            let index = pathName.substr(1).indexOf("/");
            let result = pathName.substr(0, index + 1);
            return result;
        }();
        layui.config({
            base: ctx + '/pages/admin/lib/layui_exts/'
        }).extend({
            excel: 'excel'
        });
    </script>
</head>
<body>
<div class="ok-body">
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
        <legend>专业批量导入</legend>
    </fieldset>
    <div class="layui-form-item">
        <div class="layui-upload-drag" id="test10">
            <i class="layui-icon"></i>
            <p>点击上传，或将文件拖拽到此处</p>
            <p>请选择需要导入的excel文件</p>
            <div class="layui-hide" id="uploadDemoView">
                <hr>
                <img src="" alt="上传成功后渲染" style="max-width: 196px">
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <legend style="color: #ff0000;font-size: 10px">批量数据不能为空，请完善数据后添加</legend>
    </div>
</div>
<!--展示模板-->
<script type="text/html" id="LAY-excel-export-ans">
    {{# layui.each(d.data, function(file_index, item){ }}
    <blockquote class="layui-elem-quote">{{d.files[file_index].name}}</blockquote>
    <div class="layui-tab">
        <ul class="layui-tab-title">
            {{# layui.each(item, function(sheet_name, content) { }}
            <li>{{sheet_name}}</li>
            {{# }); }}
        </ul>
        <div class="layui-tab-content">
            {{# layui.each(item, function(sheet_name, content) { }}
            <div class="layui-tab-item">
                <table class="layui-table">
                    {{# layui.each(content, function(row_index, value) { }}
                    {{# var col_index = 0 }}
                    <tr>
                        {{# layui.each(value, function(col_key, val) { }}
                        <td id="table-export-{{file_index}}-{{sheet_name}}-{{row_index}}-{{col_index++}}">{{val}}</td>
                        {{# });}}
                    </tr>
                    {{# });}}
                </table>
                <pre class="layui-code">{{JSON.stringify(content, null, 2)}}</pre>
            </div>
            {{# }); }}
        </div>
    </div>
    {{# }) }}
</script>
<script src="../../js/model.js"></script>
<script>
    layui.use(['jquery', 'layer', 'upload', 'excel', 'laytpl', 'element', 'code', "okLayer"], function () {
        let $ = layui.jquery;
        let layer = layui.layer;
        let okLayer = layui.okLayer;
        let upload = layui.upload;
        let excel = layui.excel;
        let laytpl = layui.laytpl;
        let element = layui.element;

        /**
         * 上传excel的处理函数，传入文件对象数组
         * @param  {FileList} files [description]
         * @return {[type]}       [description]
         */
        function uploadExcel(files) {
            try {
                excel.importExcel(files, {
                    // 可以在读取数据的同时梳理数据
                    fields: {
                        'professionname': 'A'
                    }
                }, function (data, book) {
                    layer.open({
                        type: 1
                        , title: '文件转换结果'
                        , area: ['799px', '399px']
                        , tipsMore: true
                        , maxmin: true
                        , content: laytpl($('#LAY-excel-export-ans').html()).render({data: data, files: files})
                        , btn: ['确定', '取消']
                        , success: function () {
                            element.render('tab')
                            layui.code({})
                            // 处理合并
                            for (var file_index in book) {
                                if (!book.hasOwnProperty(file_index)) {
                                    continue
                                }
                                // 遍历每个Sheet
                                for (var sheet_name in book[file_index].Sheets) {
                                    if (!book[file_index].Sheets.hasOwnProperty(sheet_name)) {
                                        continue
                                    }
                                    var sheetObj = book[file_index].Sheets[sheet_name]
                                    // 仅在有合并参数时进行操作
                                    if (!sheetObj['!merges']) {
                                        continue
                                    }
                                    // 遍历每个Sheet中每个 !merges
                                    for (var merge_index = 0; merge_index < sheetObj['!merges'].length; merge_index++) {
                                        var mergeObj = sheetObj['!merges'][merge_index]
                                        // 每个合并参数的 s.c 表示左上角单元格的列，s.r 表示左上角单元格的行，e.c 表示右下角单元格的列，e.r 表示右下角单元格的行，计算时注意 + 1
                                        $('#table-export-' + file_index + '-' + sheet_name + '-' + mergeObj.s.r + '-' + mergeObj.s.c)
                                            .prop('rowspan', mergeObj.e.r - mergeObj.s.r + 1)
                                            .prop('colspan', mergeObj.e.c - mergeObj.s.c + 1)
                                        for (var r = mergeObj.s.r; r <= mergeObj.e.r; r++) {
                                            for (var c = mergeObj.s.c; c <= mergeObj.e.c; c++) {
                                                // 排除左上角
                                                if (r === mergeObj.s.r && c === mergeObj.s.c) {
                                                    continue
                                                }
                                                $('#table-export-' + file_index + '-' + sheet_name + '-' + r + '-' + c).remove()
                                            }
                                        }
                                    }
                                }
                            }
                        }, yes: function (index, layero) {
                            layer.close(index);
                            //ajax运行处
                            if (data) {
                                var sheet = data[0].Sheet1;
                                var array = [];
                                for (var i = 1; i < sheet.length; i++) {
                                    array.push(new Profession(null, sheet[i].professionname));
                                }
                                $.ajax({
                                    url: ctx + '/admin/batchInsertProfession',
                                    type: 'POST',
                                    data: {"jsonProfession": JSON.stringify(array)},
                                    dataType: 'json',
                                    error: function () {
                                        okLayer.redCrossMsg("服务器错误")
                                    },
                                    success: function (data) {
                                        if (data.code == 200) {
                                            // 业务正常
                                            okLayer.greenTickMsg(data.msg)
                                        } else {
                                            // 业务异常
                                            okLayer.yellowSighMsg(data.msg)
                                        }
                                    }
                                });
                            }
                        }, btn2: function () {
                            alert("取消操作")
                        }
                    })
                })
            } catch (e) {
                layer.alert(e.message)
            }
        }


        //upload上传实例
        var uploadInst = upload.render({
            elem: '#test10' //绑定元素
            , url: '/upload/' //上传接口（PS:这里不用传递整个 excel）
            , auto: false //选择文件后不自动上传
            , accept: 'file'
            , choose: function (obj) {// 选择文件回调
                var files = obj.pushFile()
                var fileArr = Object.values(files)// 注意这里的数据需要是数组，所以需要转换一下

                // 用完就清理掉，避免多次选中相同文件时出现问题
                for (var index in files) {
                    if (files.hasOwnProperty(index)) {
                        delete files[index]
                    }
                }
                $('#test10').next().val('');

                uploadExcel(fileArr) // 如果只需要最新选择的文件，可以这样写： uploadExcel([files.pop()])
            }
        });

    })
</script>
</body>
</html>